package arithmetic;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.logging.HttpLoggingInterceptor.Level;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

/**
 * 测试http client
 */
@NoArgsConstructor
@Data
public class HttpClint {


    public static void main1(String[] args) {

       /* String content = HttpUtil.get("https://is-gateway.corp.k2uai2s2hou22w
       .com/token/get?appKey=36148355-6b3a-4f1f-9839-aa4ccb7c7b19&secretKey=C344/HuIclwLIbyRtuPgOg==&grantType
       =client_credentials");
        System.out.println(content);

        Gson gson = new Gson();
        HashMap<String, LinkedTreeMap> hashMap = gson.fromJson(content, HashMap.class);*/
        //System.out.println(hashMap.get("result").get("accessToken"));
        String token = "f6fcd7ed-c890-4625-8515-23fa5ec60f09";//(String)hashMap.get("result").get("accessToken");


        String utf8 =
                FileUtil.readUtf8String("/Users/jiangfeng/code/arithmetic/src/main/js/http/2022-02-26T094956.200.json");
        List<User> users = new Gson().fromJson(utf8, new TypeToken<List<User>>() {
        }.getType());
        System.out.println(users.size());
        File file = new File("/Users/jiangfeng/code/arithmetic/src/main/js/http/2022-02-26T094956.201.json");
        FileUtil.getWriter(file, CharsetUtil.UTF_8, true);
        for (User user : users) {

            JSONObject jsonObject = JSONUtil.parseObj(" {\n"
                    + "            \"appId\": \"83e0600f1ca235599d83712b8087b234\",\n"
                    + "                \"usernameList\": [\"" + user.getUsername()
                    + "\"],\n"
                    + "            \"ifOnlyActive\": false,\n"
                    + "                \"ifEpiboly\": true\n"
                    + "        }");

            String body =
                    HttpRequest.post("https://is-gateway.corp.k2uai2s2hou22w.com/mdata/search/employee/simple")
                            .form(jsonObject)
                            .header(Header.AUTHORIZATION, "Bearer " + token).timeout(20000)//超时，毫秒
                            .execute().body();

        }


        //System.out.println(body);

    }

    public static void main2(String[] args) {
        Gson gson = new Gson();
        String utf8 =
                FileUtil.readUtf8String("/Users/jiangfeng/code/arithmetic/src/main/js/http/2022-02-26T094956.200.json");
        List<User> users = gson.fromJson(utf8, new TypeToken<List<User>>() {
        }.getType());
        System.out.println(users.size());

        FileUtil.writeString(gson.toJson(users),
                "/Users/jiangfeng/code/arithmetic/src/main/js/http/2022-02-26T094956.201.json",
                CharsetUtil.UTF_8);

    }

    public static void main4(String[] args) {
        String token = "f6fcd7ed-c890-4625-8515-23fa5ec60f09";
        /*JSONObject jsonObject = JSONUtil.parseObj(" {\n"
                + "            \"appId\": \"83e0600f1ca235599d83712b8087b234\",\n"
                + "                \"usernameList\": [\"" +"zhaochenhui"
                + "\"],\n"
                + "            \"ifOnlyActive\": false,\n"
                + "                \"ifEpiboly\": true\n"
                + "        }");*/
        R r = new R("83e0600f1ca235599d83712b8087b234", false, true, "zhaochenhui");
        Gson gson = new Gson();

        System.out.println(gson.toJson(r));


        String content = HttpUtil.get(
                "https://is-gateway.corp.k2uai2s2hou22w"
                        + ".com/token/get?appKey=36148355-6b3a-4f1f-9839-aa4ccb7c7b19&secretKey=C344"
                        + "/HuIclwLIbyRtuPgOg==&grantType=client_credentials");
        System.out.println(content);
        Map<String, Object> o = gson.fromJson(gson.toJson(r), new TypeToken<Map<String, Object>>() {
        }.getType());
        System.out.println(o);
       /* String body =
                HttpRequest.post("https://is-gateway.corp.k2uai2s2hou22w.com/mdata/search/employee/simple")
                        .form(o)
                        .bearerAuth(token)
                        //.header(Header.AUTHORIZATION, "Bearer " + token).timeout(20000)//超时，毫秒
                        .contentType("application/json")
                        .execute()
                        .body();*/
        // System.out.println(body);
    }

    public static void main(String[] args) throws IOException {
        //  7992 wuzhaoyue-s
        //7993 yushaolong

        Builder httpClient = new Builder();
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        //httpLoggingInterceptor.level(Level.BODY);
        httpClient.addInterceptor(httpLoggingInterceptor);
        Retrofit retrofit = new Retrofit.Builder()
                //设置网络请求BaseUrl地址
                .baseUrl("https://is-gateway.corp.k2uai2s2hou22w.com/mdata/")
                .client(httpClient.build())
                //设置数据解析器
                //.addConverterFactory(JacksonConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();


        WDRetrofitClient workDayClient = retrofit.create(WDRetrofitClient.class);
        String token = "8c622ca4-da7c-4781-a5e2-02a6b6f99747";

        Gson gson = new Gson();

        String utf8 =
                FileUtil.readUtf8String(
                        "/Users/jiangfeng/code/arithmetic/src/main/js/http/2022-02-26T094956.201__.json");
        List<User> users = new Gson().fromJson(utf8, new TypeToken<List<User>>() {
        }.getType());


        int i = 0;
        int j = 0;

        PrintWriter printWriter =
                FileUtil.getPrintWriter("/Users/jiangfeng/code/arithmetic/src/main/js/http/2022-02-26T094956.205.json",
                        CharsetUtil.UTF_8, true);

        List<String> usernames = users.stream().map(e -> e.getUsername()).collect(Collectors.toList());
        int size = usernames.size();
        System.out.println(size);
        List<List<String>> partition = Lists.partition(usernames, 100);
        for (List<String> us : partition) {
           /* if (user.username.startsWith("wb")) {
                System.out.println((++j)+" 无"+user);
                continue;
            }*/
            R r = new R("83e0600f1ca235599d83712b8087b234", true, false, us);
            Call<Result<Person>> completed = workDayClient.completed("Bearer " + token, r);
            //        Call<BpmMessageDto> json = workDayClient.completed(auth, createdMomentStart, createdMomentEnd,
            //        startDate, endDate, "json");
            Response<Result<Person>> execute = completed.execute();
            if (CollectionUtils.isEmpty(execute.body().data)) {
                System.out.println((++j) + "           无" + us);
                continue;
            }

            if (i % 5000 == 0) {
                printWriter =
                        FileUtil.getPrintWriter(
                                "/Users/jiangfeng/code/arithmetic/src/main/js/http/2022-02-26T094956.205_" + i
                                        + ".json", CharsetUtil.UTF_8, true);
            }
            for (Person datum : execute.body().data) {
                printWriter.write(gson.toJson(datum));
                printWriter.write(",");
                printWriter.flush();
                System.out.println((++i) + " " + size + " " + ((float) i / size) * 100 + "% " + datum.username);
            }
        }

        System.out.println(users.size());

    }

    interface WDRetrofitClient {
        //通过HTTP注解替换GET


        // customreport2/kwai1/linxiufeng/CR_INT004_ALL_Completed_BP_Tasks?
      /*  @POST("search/employee/simple")
        Call<Result<List<Person>>> completed(@retrofit2.http.Header("Authorization") String authorization,
                @Body R r);*/
        @Headers({
                "User-Agent: Java/1.8.0_181",
        })
        @POST("search/employee/simple")
        Call<Result<Person>> completed(@retrofit2.http.Header("Authorization") String authorization,
                @Body R r);
    }


    @NoArgsConstructor
    @Data
    public static class Person {

        private String number;

        private String name;

        private String username;

        private String spellName;

        private String phone;

        private String politicalStatus;
        /**
         * areaCode
         */
        private String areaCode;
        /**
         * email
         */
        private String email;
        /**
         * personalEmail
         */
        private String personalEmail;
        /**
         * photo
         */
        private String photo;
        /**
         * photoMax
         */
        private String photoMax;
        /**
         * birthDate
         */
        private String birthDate;
        /**
         * birthplace
         */
        private String birthplace;
        /**
         * firstWorkDate
         */
        private String firstWorkDate;
        /**
         * entryDate
         */
        private String entryDate;
        /**
         * statusCode
         */
        private String statusCode;
        /**
         * statusName
         */
        private String statusName;
        /**
         * nature
         */
        private String nature;
        /**
         * employeeNatureCode
         */
        private String employeeNatureCode;
        /**
         * employeeNatureName
         */
        private String employeeNatureName;
        /**
         * displayName
         */
        private String displayName;
        /**
         * position
         */
        private String position;
        /**
         * nation
         */
        private String nation;
        /**
         * nationCode
         */
        private String nationCode;
        /**
         * politicalStatusCode
         */
        private String politicalStatusCode;
        /**
         * genderCode
         */
        private String genderCode;
        /**
         * gender
         */
        private String gender;
        /**
         * nationality
         */
        private String nationality;
        /**
         * marriage
         */
        private String marriage;
        /**
         * marriageCode
         */
        private String marriageCode;
        /**
         * cityName
         */
        private String cityName;
        /**
         * workCity
         */
        private String workCity;
        /**
         * workCityName
         */
        private String workCityName;
        /**
         * workPlace
         */
        private String workPlace;
        /**
         * workPlaceName
         */
        private String workPlaceName;
        /**
         * ifFrontLine
         */
        private String ifFrontLine;
        /**
         * frontLineTypeName
         */
        private String frontLineTypeName;
        /**
         * frontLineType
         */
        private String frontLineType;
        /**
         * leaderNumber
         */
        private String leaderNumber;
        /**
         * leaderName
         */
        private String leaderName;
        /**
         * leaderUsername
         */
        private String leaderUsername;
        /**
         * hrbpNumber
         */
        private String hrbpNumber;
        /**
         * hrbpUsername
         */
        private String hrbpUsername;
        /**
         * hrbpName
         */
        private String hrbpName;
        /**
         * departments
         */
        private List<String> departments;
        /**
         * departmentCode
         */
        private String departmentCode;
        /**
         * departmentName
         */
        private String departmentName;
        /**
         * companyCode
         */
        private String companyCode;
        /**
         * companyName
         */
        private String companyName;
        /**
         * contractCompany
         */
        private String contractCompany;
        /**
         * contractCompanyCode
         */
        private String contractCompanyCode;
        /**
         * contractStartDate
         */
        private String contractStartDate;
        /**
         * contractEndDate
         */
        private String contractEndDate;
        /**
         * tutorNumber
         */
        private String tutorNumber;
        /**
         * tutorName
         */
        private String tutorName;
        /**
         * recruitChannel
         */
        private String recruitChannel;
        /**
         * recruitChannelName
         */
        private String recruitChannelName;
        /**
         * mealSubsidy
         */
        private String mealSubsidy;
        /**
         * lastUpdateTime
         */
        private String lastUpdateTime;
        /**
         * educations
         */
        private List<EducationsDTO> educations;
        /**
         * workExperiences
         */
        private List<WorkExperiencesDTO> workExperiences;
        /**
         * personBank
         */
        private PersonBankDTO personBank;
        /**
         * familyContacts
         */
        private List<FamilyContactsDTO> familyContacts;
        /**
         * personEmergencyContacts
         */
        private List<PersonEmergencyContactsDTO> personEmergencyContacts;
        /**
         * residence
         */
        private ResidenceDTO residence;
        /**
         * visa
         */
        private VisaDTO visa;
        /**
         * personAddress
         */
        private PersonAddressDTO personAddress;
        /**
         * contractType
         */
        private String contractType;
        /**
         * buId
         */
        private String buId;
    }

    /**
     * PersonBankDTO
     */
    @NoArgsConstructor
    @Data
    public static class PersonBankDTO {
        /**
         * id
         */
        private Integer id;
        /**
         * accountNumber
         */
        private String accountNumber;
        /**
         * bank
         */
        private String bank;
        /**
         * bankCode
         */
        private String bankCode;
        /**
         * accountOwner
         */
        private String accountOwner;
    }

    /**
     * ResidenceDTO
     */
    @NoArgsConstructor
    @Data
    public static class ResidenceDTO {
        /**
         * residenceTypeName
         */
        private String residenceTypeName;
        /**
         * residenceType
         */
        private String residenceType;
        /**
         * residenceDesc
         */
        private String residenceDesc;
    }

    /**
     * VisaDTO
     */
    @NoArgsConstructor
    @Data
    public static class VisaDTO {
        /**
         * id
         */
        private Integer id;
        /**
         * certificateType
         */
        private String certificateType;
        /**
         * certificateTypeName
         */
        private String certificateTypeName;
        /**
         * certificateNumber
         */
        private String certificateNumber;
        /**
         * expiredDate
         */
        private String expiredDate;
    }

    /**
     * PersonAddressDTO
     */
    @NoArgsConstructor
    @Data
    public static class PersonAddressDTO {
        /**
         * countryCode
         */
        private String countryCode;
        /**
         * country
         */
        private String country;
        /**
         * address
         */
        private String address;
    }

    /**
     * EducationsDTO
     */
    @NoArgsConstructor
    @Data
    public static class EducationsDTO {
        /**
         * id
         */
        private Integer id;
        /**
         * personId
         */
        private String personId;
        /**
         * userId
         */
        private String userId;
        /**
         * degree
         */
        private String degree;
        /**
         * degreeName
         */
        private String degreeName;
        /**
         * entranceDate
         */
        private String entranceDate;
        /**
         * graduationDate
         */
        private String graduationDate;
        /**
         * major
         */
        private String major;
        /**
         * educationLocation
         */
        private String educationLocation;
        /**
         * educationLocationName
         */
        private String educationLocationName;
        /**
         * schoolName
         */
        private String schoolName;
        /**
         * professionName
         */
        private String professionName;
        /**
         * isDegree
         */
        private Boolean isDegree;
        /**
         * ehrCreateTime
         */
        private String ehrCreateTime;
        /**
         * ehrUpdateTime
         */
        private String ehrUpdateTime;
        /**
         * createTime
         */
        private String createTime;
        /**
         * lastUpdateTime
         */
        private String lastUpdateTime;
    }

    /**
     * WorkExperiencesDTO
     */
    @NoArgsConstructor
    @Data
    public static class WorkExperiencesDTO {
        /**
         * id
         */
        private Integer id;
        /**
         * personId
         */
        private String personId;
        /**
         * userId
         */
        private String userId;
        /**
         * startDate
         */
        private String startDate;
        /**
         * endDate
         */
        private String endDate;
        /**
         * companyName
         */
        private String companyName;
        /**
         * duty
         */
        private String duty;
        /**
         * workDistrict
         */
        private String workDistrict;
        /**
         * workDistrictName
         */
        private String workDistrictName;
        /**
         * superiorName
         */
        private String superiorName;
        /**
         * isRelieveRelationship
         */
        private Boolean isRelieveRelationship;
        /**
         * isCompetitionRestrict
         */
        private Boolean isCompetitionRestrict;
        /**
         * ehrCreateTime
         */
        private String ehrCreateTime;
        /**
         * ehrUpdateTime
         */
        private String ehrUpdateTime;
        /**
         * createTime
         */
        private String createTime;
        /**
         * lastUpdateTime
         */
        private String lastUpdateTime;
    }

    /**
     * FamilyContactsDTO
     */
    @NoArgsConstructor
    @Data
    public static class FamilyContactsDTO {
        /**
         * id
         */
        private Integer id;
        /**
         * personId
         */
        private String personId;
        /**
         * relationship
         */
        private String relationship;
        /**
         * relationshipName
         */
        private String relationshipName;
        /**
         * name
         */
        private String name;
        /**
         * gender
         */
        private String gender;
        /**
         * isDependent
         */
        private Boolean isDependent;
        /**
         * workUnit
         */
        private String workUnit;
        /**
         * phone
         */
        private String phone;
        /**
         * ehrCreateTime
         */
        private String ehrCreateTime;
        /**
         * ehrUpdateTime
         */
        private String ehrUpdateTime;
        /**
         * createTime
         */
        private String createTime;
        /**
         * lastUpdateTime
         */
        private String lastUpdateTime;
    }

    /**
     * PersonEmergencyContactsDTO
     */
    @NoArgsConstructor
    @Data
    public static class PersonEmergencyContactsDTO {
        /**
         * id
         */
        private Integer id;
        /**
         * personId
         */
        private String personId;
        /**
         * relationship
         */
        private String relationship;
        /**
         * relationshipCode
         */
        private String relationshipCode;
        /**
         * name
         */
        private String name;
        /**
         * phone
         */
        private String phone;
        /**
         * isPrimary
         */
        private Boolean isPrimary;
        /**
         * createdDate
         */
        private String createdDate;
        /**
         * lastModifiedDate
         */
        private String lastModifiedDate;
    }

    class User {
        //private String id;
        private String username;

        public String getUsername() {
            return username;
        }

        public User() {
        }
    }

    @Data
    class Result<T> {
        int result;
        String message;
        List<T> data;
    }


    @Data
    static class R {
        public R(String appId, boolean ifEpiboly, boolean ifOnlyActive, String username) {
            this.appId = appId;
            this.ifEpiboly = ifEpiboly;
            this.ifOnlyActive = ifOnlyActive;
            this.usernameList = Lists.newArrayList(username);
        }

        public R(String appId, boolean ifEpiboly, boolean ifOnlyActive, List<String> usernameList) {
            this.appId = appId;
            this.ifEpiboly = ifEpiboly;
            this.ifOnlyActive = ifOnlyActive;
            this.usernameList = usernameList;
        }

        /* {"usernameList":["zhaochenhui"],
                    "appId":"83e0600f1ca235599d83712b8087b234",
                        "ifEpiboly":true,
                        "ifOnlyActive":false
                }*/
        //private String id;
        private String appId;
        private boolean ifEpiboly;
        private boolean ifOnlyActive;
        private List<String> usernameList;
    }


}
